<?php
class Xmpp_redis extends Common_redis_model{
	public function __construct(array $params = array()) 
	{
		parent::__construct();
		$this->params=$params;
	}
	//获取房间历史人
	function get_room_history_by_members($uid = 0) {
		$redis_room_key		= $this->params['channel'] .":room_history_members:live-chat-".$uid;
		$redis_room_list	= $this->redis->sMembers($redis_room_key);
		return $redis_room_list;
	}
	//获取房间历史人
	function get_room_history_by_members_temp($uid = 0) {
		$redis_room_key		= $this->params['channel'] .":room_history_members_temp:live-chat-".$uid;
		$redis_room_list	= $this->redis->sMembers($redis_room_key);
		return $redis_room_list;
	}
	function del_room_history_by_members_temp($uid = 0) {
		$redis_room_key		= $this->params['channel'] .":room_history_members_temp:live-chat-".$uid;
		$this->redis->delete($redis_room_key);
	}
	//获取用户加入房间历史
	function get_user_joined_room_by_uid($uid = 0) {
		$redis_user_room_key	= $this->params['channel'] .":user_joined_room_history:".$uid;
		$redis_user_room_list	= $this->redis->hgetall($redis_user_room_key);
		return $redis_user_room_list;
	}
	//获取房间在线人
	function get_room_current_members($uid = 0) {
		$redis_room_current_key		= $this->params['channel'] .":room_current_members:live-chat-".$uid;
		$redis_room_current_list	= $this->redis->sMembers($redis_room_current_key);
		return $redis_room_current_list;
	}
	//返回房间信息
	function return_room_member ($uid = 0,$user_info = array(),$result = array() ) {
		
		$this->CI->load->config('xmpp_config',TRUE);
		$xmpp = $this->CI->config->item('data', 'xmpp_config');
		
		//xmpp 注册账号
		if(empty($user_info['is_reg_xmpp'])) {
			try {
				$xmpp_rest_url = $xmpp['Server'].':'.$xmpp['RestPORT'].'/rest/adhoc/sess-man@'.$xmpp['Domain'];
				$header = array();
				$header[] = 'Authorization: '.$xmpp['RestAuthorization'];
				$header[] = 'Content-Type: application/json';
				
				$xmpp_password = create_rand_str(12, 30);
				$post_data = array(
					"command" =>  array(
						"node"		=> "http://jabber.org/protocol/admin#add-user",
						"fields"	=> array(
							array("var"	=> "accountjid","value"	=> $user_info['uid'] .'@'.$xmpp['Domain']),
							array("var"	=> "password", "value"	=> $xmpp_password ))
						)
					);
				/*
				print_r($post_data);exit;
				$dom		= new DOMDocument('1.0','utf-8');
				$command	= $dom->createElement("command");
				$node 		= $dom->createElement("node","http://jabber.org/protocol/admin#add-user");
				$fields		= $dom->createElement("fields");
				$item_jid	= $dom->createElement("item");
				$item_pwd	= $dom->createElement("item");
				
				$command->appendChild($node);
				//jid
				$item_jid->appendChild( $dom->createElement("var","accountjid"));
				$item_jid->appendChild( $dom->createElement("value", $user_info['uid'] .'@'.$xmpp['Domain']));
				$fields->appendChild($item_jid);
				//pwd
				$item_pwd->appendChild( $dom->createElement("var","password"));
				$item_pwd->appendChild( $dom->createElement("value",  create_rand_str(6, 30) ));
				$fields->appendChild($item_pwd);
				
				$command->appendChild($fields);
				
				$dom->appendChild($command);
				$dom->saveXML()
				*/
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
				curl_setopt($ch, CURLOPT_URL, $xmpp_rest_url);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
				//设置curl_exec返回的值包含Http头
				curl_setopt($ch, CURLOPT_HEADER, 0);
				//设置curl_exec返回的值包含Http内容
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       
				//设置抓取跳转（http 301，302）后的页面
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				//设置最多的HTTP重定向的数量
				curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
				
				curl_setopt($ch, CURLOPT_TIMEOUT,10);
			
				//服务器返回的数据
				$response = curl_exec($ch);
				
				if(!empty($response)) {
					$response = json_decode($response, true);
					
					if(!empty($response['command']['fields'])) {
						foreach($response['command']['fields'] as $key=>$val) {
							if( (int) $val['value'] == 1) {
								$user_id=(int)$user_info['uid'];
								$data = array();
								$data['xmpp_password'] = $user_info['xmpp_password'] = $xmpp_password;
								$data['is_reg_xmpp'] = $user_info['is_reg_xmpp'] = 1;
								
								$this->CI->db->where('id', (int)$user_info['uid']);
								$this->CI->db->update('user', $data);
								
								//注册xmpp主播房间
								$anchor_xmpp=$this->do_anchor_xmpp_reg($user_id,$user_id);
							}
						}
					}
				}
			}catch (Exception $e) {
				echo $e->getmessage();
			}
		}
		//重新check
		if(!empty($user_info['is_reg_xmpp'])) {
			$result['result_data']['xmpp_domain']				= $xmpp['Domain'];
			$result['result_data']['xmpp_server']				= $xmpp['Server'];
			$result['result_data']['xmpp_port']					= $xmpp['PORT'];
			$result['result_data']['xmpp_client_key']			= isset($xmpp['CKEY'])?$xmpp['CKEY']:'';
			$result['result_data']['xmpp_server_key']			= isset($xmpp['SKEY'])?$xmpp['SKEY']:'';
			$result['result_data']['xmpp_room_domain']			= $xmpp['RoomDomain'].$xmpp['Domain'];
			$result['result_data']['xmpp_live_chat_id']			= 'live-chat-'.$uid;
			$result['result_data']['xmpp_nick']              	= !empty($user_info['nick']) ? $user_info['nick'] : '';
			$result['result_data']['xmpp_username']				= !empty($user_info['uid']) ? $user_info['uid'] : '';
			$result['result_data']['xmpp_password']				= !empty($user_info['xmpp_password']) ? $user_info['xmpp_password'] : '';
		}
		return $result;
	}
	
	//注册主播xmpp房间
	private function do_anchor_xmpp_reg($anchor_id=0, $uid=0){
		if(empty($anchor_id)||empty($uid)) return false;
		
		$this->CI->load->config('xmpp_config',TRUE);
		$xmpp = $this->CI->config->item('data', 'xmpp_config');
		
		//xmpp 注册账号
		try {
			$xmpp_rest_url = $xmpp['Server'].':'.$xmpp['RestPORT'].'/rest/adhoc/muc@muc.'.$xmpp['Domain'];
			$header = array();
			$header[] = 'Authorization: '.$xmpp['RestAuthorization'];
			$header[] = 'Content-Type: application/json';
			$post_data = array(
				"command" =>  array(
					"jid"		=> "muc@muc.".$xmpp['Domain'],
					"node"		=> "create-room",
					"fields"	=>  array(
						array('var' => "roomjid" ,'label' => "jid-single" ,'value' => "live-chat-".$anchor_id."@muc.".$xmpp['Domain'] ),
						array('var' => "owner" ,'label' => "jid-single" ,'value' => "".$uid."@".$xmpp['Domain'] ),
						array('var' => "nick" ,'label' => "text-single" ,'value' => "$uid")
						)			
					)
				);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_URL, $xmpp_rest_url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
			//设置curl_exec返回的值包含Http头
			curl_setopt($ch, CURLOPT_HEADER, 0);
			//设置curl_exec返回的值包含Http内容
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       
			//设置抓取跳转（http 301，302）后的页面
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			//设置最多的HTTP重定向的数量
			curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
			curl_setopt($ch, CURLOPT_TIMEOUT,10);
			//服务器返回的数据
			$response = curl_exec($ch);
			if(!empty($response)) {
				return true;
			}else{
				write_to_db_logs('anchor_reg_xmpp_response_error_'.$uid,$response);
			}
		}catch (Exception $e) {
			//echo $e->getmessage();
			write_to_db_logs('anchor_reg_xmpp_error_'.$uid,$e->getmessage());
			return false;
		}
	}
	
	
}